package com.boyuan.huijiaoyu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.boyuan.huijiaoyu.R;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.constant.Constant;


public class UpdateVersionService extends Service{
	
	//服务端版本
	private int serverVersionNum = 1;
		
	//.apk下载地址
	private String clientUrlPath="";
	
	
	//下载目录
	private File updateDir = null;
	private File updateFile = null;
	 
	//通知
	private NotificationManager updateNotificationManager = null;
	private Notification updateNotification = null;
	//Intent
	private Intent updateIntent = null;
	private PendingIntent updatePendingIntent = null;
	
	private final static int DOWNLOAD_COMPLETE = 0;
	private final static int DOWNLOAD_FAIL = 1;
	
	private String downloading;
	private String startdownload;
	private String downloaded;
	private String appName;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {


		Log.e("update service", "onStartCommand");
		
	    serverVersionNum=Integer.parseInt(SharePreferenceHelper.getStringValue(getApplicationContext(), SharePreferenceHelper.SERVERVERSIONNUM));
	    
	    clientUrlPath=SharePreferenceHelper.getStringValue(getApplicationContext(), SharePreferenceHelper.CLIENTURLPATH);
	    
	    downloading=getResources().getString(R.string.vision_downloading);
	    startdownload=getResources().getString(R.string.vision_startdownload);
	    downloaded=getResources().getString(R.string.vision_completedownload);
	    appName=getResources().getString(R.string.app_name);
	    
	    //判断是否有外部存储
	    if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){
	    	Date date=new Date();
	    	String dateString=""+(date.getMonth()+1)+date.getDay()+date.getHours()+date.getMinutes()+date.getSeconds();
	        updateDir = new File(Environment.getExternalStorageDirectory(),Constant.downloadDir);
	        //TODO:文件名需要修改
	        updateFile = new File(updateDir.getPath(),"CardToon"+dateString+".apk");
	    }
	 
	    this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	    this.updateNotification = new Notification();
	 
	    updateIntent = new Intent(this, MainActivity.class);
	    updatePendingIntent = PendingIntent.getActivity(this,0,updateIntent,0);

	    updateNotification.icon =R.drawable.ic_launcher1;
	    updateNotification.tickerText = startdownload;
	    updateNotification.setLatestEventInfo(this,appName,"0%",updatePendingIntent);
	    updateNotificationManager.notify(0,updateNotification);
	 
	    //使用新线程去下载
	    new Thread(new updateRunnable()).start();
	     
	    return super.onStartCommand(intent, flags, startId);
	}
	
	private Handler updateHandler = new  Handler(){
	    @Override
	    public void handleMessage(Message msg) {
	    	switch(msg.what){
            case DOWNLOAD_COMPLETE:
                //下载完毕后安装
                Uri uri = Uri.fromFile(updateFile);
                Intent installIntent = new Intent(Intent.ACTION_VIEW);
                installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                updatePendingIntent = PendingIntent.getActivity(UpdateVersionService.this, 0, installIntent, 0);
                 
                updateNotification.defaults = Notification.DEFAULT_SOUND;//默认声音 
                updateNotification.setLatestEventInfo(UpdateVersionService.this, appName, downloaded, updatePendingIntent);
                updateNotificationManager.notify(0, updateNotification);
                 
                //停止服务
                stopService(updateIntent);
            case DOWNLOAD_FAIL:
                //下载失败处理
                updateNotification.setLatestEventInfo(UpdateVersionService.this, appName, downloaded, updatePendingIntent);
                updateNotificationManager.notify(0, updateNotification);
            default:
                stopService(updateIntent);
        }
   
	    }
	};
	
	class updateRunnable implements Runnable {
        Message message = updateHandler.obtainMessage();
        @Override
		public void run() {
            message.what = DOWNLOAD_COMPLETE;
            try{
                //<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">;
                if(!updateDir.exists()){
                    updateDir.mkdirs();
                }
                if(!updateFile.exists()){
                    updateFile.createNewFile();
                }

                //<uses-permission android:name="android.permission.INTERNET">;
                long downloadSize = downloadUpdateFile(clientUrlPath,updateFile);
                if(downloadSize>0){
                    //下载完毕通知
                    updateHandler.sendMessage(message);                  
                    //SharePreferenceHelper.setStringValue(getApplicationContext(), SharePreferenceHelper.LOCALVERSIONNUM, ""+serverVersionNum);
                }
            }catch(Exception ex){
                ex.printStackTrace();
                message.what = DOWNLOAD_FAIL;
                //下载失败通知
                updateHandler.sendMessage(message);
            }
        }
    }
	
	//下载文件
	public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
        
        int downloadCount = 0;
        int currentSize = 0;
        long totalSize = 0;
        int updateTotalSize = 0;
         
        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
         
        try {
            URL url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection)url.openConnection();
            httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
            if(currentSize > 0) {
                httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
            }
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(20000);
            updateTotalSize = httpConnection.getContentLength();
            if (httpConnection.getResponseCode() == 404) {
                throw new Exception("fail!");
            }
            is = httpConnection.getInputStream();                   
            fos = new FileOutputStream(saveFile, false);
            byte buffer[] = new byte[4096];
            int readsize = 0;
            while((readsize = is.read(buffer)) > 0){
                fos.write(buffer, 0, readsize);
                totalSize += readsize;
                //更新下载进度 eg:10%
                if((downloadCount == 0)||(int) (totalSize*100/updateTotalSize)-10>downloadCount){ 
                    downloadCount += 10;
                    updateNotification.setLatestEventInfo(UpdateVersionService.this, downloading, (int)totalSize*100/updateTotalSize+"%", updatePendingIntent);
                    updateNotificationManager.notify(0, updateNotification);
                }                        
            }
        } finally {
            if(httpConnection != null) {
                httpConnection.disconnect();
            }
            if(is != null) {
                is.close();
            }
            if(fos != null) {
                fos.close();
            }
        }
        return totalSize;
    }
	
	@Override
	public void onDestroy() {
		
		super.onDestroy();
	}
	
	
	
}
